<?php
namespace app\common\service;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\common\model\SmsModel;
use Darabonba\OpenApi\Models\OpenApiRequest;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class AliSms
{
    const URL = 'https://dysmsapi.aliyuncs.com/';
    const SignName = '星际旅行';

    const KEYID = 'LTAI5tJmwKgA3iwYW8nojhq4';
    const KEYSECRET = 'VagWPUucT9tUkAoyGZtZlvgE3may05';

    const TEMPLATECODE        = 'SMS_228545012';  //短信验证码
    const TEMPLATECODE_ACTION = '';  //验证码--场景


    const TEMPLATECODE_NOTICE = 'SMS_216825910';  //通知提示

    const PRODUCT = 'Dysmsapi';
    const REGION = "cn-hangzhou";

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient(){
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => self::KEYID,
            // 您的AccessKey Secret
            "accessKeySecret" => self::KEYSECRET
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new MyDysmsapi($config);
    }

    /**
     * 发送短信验证码
     * @param $code
     * @param $mobile
     * @return
     */
    public static function send($code, $mobile)
    {
//        return self::smsSend($mobile,self::TEMPLATECODE,"{'code':${code}}");

        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => "".$mobile,
            "signName" => self::SignName,
            "templateCode" => self::TEMPLATECODE,
            "templateParam" => "{'code':${code}}"
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $response = $client->sendSms($sendSmsRequest);
        return $response->body->message;
    }
}

class MyDysmsapi extends Dysmsapi{

    /**
     * @param SendSmsRequest $request
     * @param RuntimeOptions $runtime
     *
     * @return SendSmsResponse
     */
    public function sendSmsWithOptions($request, $runtime)
    {
        Utils::validateModel($request);
        $req = new OpenApiRequest([
            'body' => Utils::toMap($request),
        ]);

        return SendSmsResponse::fromMap($this->doRPCRequest('SendSms', '2017-05-25', 'HTTP', 'POST', 'AK', 'json', $req, $runtime));
    }
}